package com.carl.guli.interceptor;

import com.carl.guli.common.constant.Constant;
import com.carl.guli.common.exception.AuthorizationException;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by youzm on 2017/3/18.
 */
public class AccountInterceptor implements HandlerInterceptor {

    private List<String> excludedUrls;

    public void setExcludedUrls(List<String> excludedUrls) {
        this.excludedUrls = excludedUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String requestUri = request.getRequestURI();
        for (String url : excludedUrls) {
            if (requestUri.indexOf(url) >= 0) {
                return true;
            }
        }

        // intercept
        HttpSession session = request.getSession();
        if (session.getAttribute(Constant.CACHE_ACCOUNT) == null) {
            throw new AuthorizationException();
        } else {
            return true;
        }
//        httpServletResponse.setHeader("Access-Control-Allow-Origin","*");
//        httpServletResponse.setHeader("Access-Control-Allow-Methods","POST");
//        httpServletResponse.setHeader("Access-Control-Allow-Headers","Access-Control");
//        httpServletResponse.setHeader("Allow","POST");

//        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
